/**
 *  Copyright 2013 University Pierre & Marie Curie - UMR CNRS 7606 (LIP6/MoVe)
 *  All rights reserved.   This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Initial contributor:
 *    Lom M. Hillah - <lom-messan.hillah@lip6.fr>
 *
 *  Mailing list:
 *    lom-messan.hillah@lip6.fr
 */
package fr.lip6.msr4j.asf.utils.parsers;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cern.colt.Arrays;

import fr.lip6.msr4j.asf.utils.config.DataSourcesConfig;
import fr.lip6.msr4j.utils.parsers.HTMLPageParser;

public class ASFSVNURLIndexParser extends HTMLPageParser<File> {
	private static final double NANO = 1.0e9;
	@Override
	public File parseIndex() {
		PrintWriter pw = null;
		File svnUrls = new File(DataSourcesConfig.getSvnProperties());
		logger.info("Start parsing the page at: "
				+ DataSourcesConfig.getSvnIndexLocal());
		final long start = System.nanoTime();
		try {
			if (!svnUrls.exists()) {
				svnUrls.createNewFile();
			}
			if (svnUrls.isFile()) {
				pw = new PrintWriter(new BufferedWriter(new FileWriter(svnUrls,
						true)));
				Document doc = loadDocumentFromLocal(
						DataSourcesConfig.getSvnIndexLocal(),
						DataSourcesConfig.getSvnIndexBase(),
						DataSourcesConfig.UTF8);
				Element ul = doc.getElementsByTag("ul").first();
				Elements lis = ul.getElementsByTag("li");
				String svnName, svnurl;
				for (Element li : lis) {
					Element a = li.getElementsByTag("a").first();
					svnName = a.text();
					svnName = a.text().substring(0, svnName.length() - 1);
					svnurl = DataSourcesConfig.getSvnIndexBase() + svnName;
					pw.println(svnName + "=" + svnurl);
				}
				pw.flush();
			} else {
				logger.error("No SVN URL properties file found.");
			}
			final long end = System.nanoTime();
			logger.info("Finished parsing operation. Time taken: "
					+ (end - start) / NANO);
		} catch (IOException e) {
			logger.error(e.getMessage());
			logger.error(Arrays.toString(e.getStackTrace()));
		} finally {
			if (pw != null) {
				pw.close();
			}
		}
		return svnUrls;
	}

}
